from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time
import json
import os
from pathlib import Path
from setting import *

headless = True
cookies_file = 'weibo_cookies2.json'

# 方法1: 基本读取
def read_json_file(filename):
    """读取JSON文件并返回Python对象"""
    try:
        with open(filename, 'r', encoding='utf-8') as file:
            data = json.load(file)
            return data
    except FileNotFoundError:
        print(f"错误: 文件 '{filename}' 不存在")
        return None
    except json.JSONDecodeError as e:
        print(f"错误: JSON 解析失败 - {e}")
        return None
    except Exception as e:
        print(f"错误: 读取文件时发生异常 - {e}")
        return None


def init_driver(driver_path):
    """初始化浏览器驱动"""
    chrome_options = Options()
    if headless:
        chrome_options.add_argument('--headless')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument('--disable-blink-features=AutomationControlled')
    chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
    chrome_options.add_experimental_option('useAutomationExtension', False)
    chrome_options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36')
    
    try:
        # 启动 driver
        service = Service(driver_path)
        driver = webdriver.Chrome(service=service, options=chrome_options)
        driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
        return driver  # 重要：返回driver对象
    except Exception as e:
        print(f"浏览器驱动初始化失败: {e}")
        return None

def get_specific_cookies():
    """获取特定的Cookie值"""
    driver = init_driver(Path.cwd() / DRIVER_PATH)  # 接收返回的driver对象
    if not driver:
        return None
    
    try:
        # 访问微博
        print("正在加载微博页面...")
        driver.get('https://weibo.com')
        time.sleep(10)
        
        # 模拟用户行为
        driver.execute_script("window.scrollTo(0, 500);")
        time.sleep(2)
        driver.execute_script("window.scrollTo(500, 1000);")
        time.sleep(2)
        
        # 获取Cookie
        cookies = driver.get_cookies()
        
        # 提取目标Cookie
        target_cookies = {}
        for cookie in cookies:
            if cookie['name'] in ['ALF', 'SCF', 'SUB', 'SUBP', 'WBPSESS', 'XSRF-TOKEN']:
                target_cookies[cookie['name']] = cookie['value']
                print(f"✅ 找到 {cookie['name']}")
        
        # 保存到文件
        save_cookies(cookies)

        #保存文件
        json_data = read_json_file('auth_state.json')
        cookies=json_data.get("cookies");
        data={}
        for key, value in enumerate(cookies):
            data[value['name']] = value['value']

        file_path = 'weibo_cookies.json'
        # 写入JSON数据到文件
        with open(file_path, 'w') as file:
            json.dump(data, file, indent=4)

        
        return target_cookies
        
    except Exception as e:
        print(f"获取Cookie失败: {e}")
        return None
    finally:
        if driver:
            driver.quit()

def save_cookies(cookies):
    """保存Cookie到文件"""
    with open(cookies_file, 'w', encoding='utf-8') as f:
        json.dump(cookies, f, ensure_ascii=False, indent=2)
    print(f"Cookie已保存到: {cookies_file}")

def load_cookies():
    """从文件加载Cookie"""
    if os.path.exists(cookies_file):
        with open(cookies_file, 'r', encoding='utf-8') as f:
            return json.load(f)
    return None

# 使用示例
if __name__ == "__main__":
    target_cookies = get_specific_cookies()
    print(f"✅ cookie已成功保存到文件: weibo_cookies.json")
